<template>
  <div id="addPicture">
    <h2 style="margin-bottom: 16px">{{ route.query?.id ? '修改图片' : '创建图片' }}</h2>
    <a-typography-paragraph v-if="spaceId" type="secondary">
      保存至空间：
      <a href="/space/{{ spaceId }}" target="_blank">
        {{ spaceId }}
      </a>
    </a-typography-paragraph>
    <!-- 选择上传方式 -->
    <a-tabs v-model:activeKey="uploadType">
      <a-tab-pane key="file" tab="文件上传">
        <PictureUpload :picture="filePicture" :onSuccess="onFileSuccess" :spaceId="spaceId" />
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL 上传" force-render>
        <UrlPictureUpload :picture="urlPicture" :onSuccess="onUrlSuccess" :spaceId="spaceId" />
      </a-tab-pane>
    </a-tabs>
    <a-form :model="pictureForm" @finish="handleSubmit" layout="vertical">
      <a-form-item label="名称" name="name">
        <a-input v-model:value="pictureForm.name" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item label="简介" name="introduction">
        <a-textarea
          v-model:value="pictureForm.introduction"
          placeholder="请输入简介"
          :rows="2"
          autoSize
          allowClear
        />
      </a-form-item>
      <a-form-item label="分类" name="category">
        <a-auto-complete
          v-model:value="pictureForm.category"
          placeholder="请输入分类"
          allowClear
          :options="categoryOptions"
        />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="pictureForm.tags"
          placeholder="请输入标签"
          mode="tags"
          :options="tagOptions"
          allowClear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">创建</a-button>
      </a-form-item>
    </a-form>
    <div v-if="picture" class="edit-bar">
      <a-space>
        <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
        <ImageCropper
          ref="imageCropperRef"
          :imagesUrl="picture?.url"
          :picture="picture"
          :spaceId="spaceId"
          :onSuccess="onCropSuccess"
        />
      </a-space>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  getTagCategoryUsingGet,
} from '@/api/pictureController'
import ImageCropper from '@/components/ImageCropper.vue'
import router from '@/router'
import { EditOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { computed, h, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import PictureUpload from './PictureUpload.vue'
import UrlPictureUpload from './UrlPictureUpload.vue'
const uploadType = ref<'file' | 'url'>('file')

//定义属性
const pictureForm = reactive<API.PictureEditRequest>({})
const picture = ref<API.PictureVO>()
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])
const route = useRoute()
const spaceId = computed(() => {
  return route.query?.spaceId
})
const filePicture = ref<API.PictureVO>()
const urlPicture = ref<API.PictureVO>()

const activePicture = computed(() => {
  return uploadType.value === 'file' ? filePicture.value : urlPicture.value
})
const onFileSuccess = (newPicture: API.PictureVO) => {
  filePicture.value = newPicture
  pictureForm.name = newPicture.name
  picture.value = newPicture
}
const onUrlSuccess = (newPicture: API.PictureVO) => {
  urlPicture.value = newPicture
  pictureForm.name = newPicture.name
  picture.value = newPicture
}
const getTagCategoryOptions = async () => {
  const res = await getTagCategoryUsingGet()
  console.log('标签和分类', res)
  if (res.data.code === 0 && res.data.data) {
    //转换成下拉框接受的数据格式
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('加载失败' + res.data.message)
  }
}
/**
 * 图片的旧数据
 */
const getOldPicture = async () => {
  const id = route.query?.id
  if (id) {
    const res = await getPictureVoByIdUsingGet({ id: id })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.category = data.category
      pictureForm.tags = data.tags || []
      filePicture.value = data
      uploadType.value = 'file'
    }
  }
}
/**
 * 提交表单
 */
const handleSubmit = async (values: any) => {
  console.log('提交表单', values)
  const pictureId = route.query?.id ? Number(route.query.id) : activePicture.value?.id
  if (!pictureId) {
    return
  }
  const res = await editPictureUsingPost({
    id: pictureId,
    spaceId: spaceId.value,
    ...values,
  })
  console.log('提交结果', res)
  if (res.data.code === 0 && res.data.data) {
    message.success('创建成功')
    //跳转到图片详情页
    router.push({
      path: `/picture/${pictureId}`,
    })
  } else {
    message.error('创建失败' + res.data.message)
  }
}

const imageCropperRef = ref()

const doEditPicture = () => {
  // 先判断 picture 存在（子组件已渲染），且 ref 实例有效
  if (picture.value && imageCropperRef.value?.openModal) {
    imageCropperRef.value.openModal()
  } else {
    // 提示用户“图片未加载完成，无法编辑”
    message.warning('请先上传或加载图片')
  }
}
const onCropSuccess = (newPicture: API.PictureVO) => {
  filePicture.value = newPicture
  pictureForm.name = newPicture.name
}
onMounted(() => {
  getTagCategoryOptions()
  getOldPicture()
})
</script>

<style lang="scss" scoped>
#addPicture {
  max-width: 720px;
  margin: 0 auto;

  .edit-bar {
    text-align: center;
    margin-top: 16px 0;
  }
}
</style>
